<template>
<q-page ref="reccePage" :style="isShow?'position:absolute;top:60px;left:0px;right:0px;bottom:40px;min-height:10px':'position:absolute;top:0px;left:0px;right:0px;bottom:0px;min-height:10px'">
    <div id="three">

    </div>
    <div class="row fixed-top-right" style="margin-top:60px">

    </div>
    <!-- <q-page-sticky v-if="user.right >=2" position="bottom-right" :offset="[50,50]">
      <q-btn dense rounded class="shadow-7 q-px-md translucence" color="white" @click="handleCreateDialog" :disable="draggingFab" stack text-color="primary">
          <q-icon size="15px" name="add"></q-icon>
          <div class="text-caption">上传堪景</div>
      </q-btn>
  </q-page-sticky> -->
</q-page>
</template>

<script>
import * as THREE from "assets/js/three/build/three.module";
import "assets/js/three/js/libs/timeliner_gui.min.js";
import {
    OrbitControls
} from "assets/js/three/jsm/controls/OrbitControls.js";
import {
    TransformControls
} from "assets/js/three/jsm/controls/TransformControls";

export default {
    name: 'ReccePage',
    props: {
        user: {
            type: Object
        },
        isShow:{
          default:true
        }
    },
    data() {
        return {
            scene: {},
            camera: {},
            orbit: {},
            renderer: {},
            control: {},
            cameraPersp: {},
            model: {},
            mixer: {},
            clock: {},
            actions: [],
            transformMode: "t",
            objects: [],
            sceneHelpers: {},
            helpers: [],
            signals: {},
        };
    },
    created() {
        console.log("启动");
    },
    mounted() {
        setTimeout(() => {
            this.loadPreviewSys();
        }, 200)

    },


    methods: {
        onWindowResize() {
            setTimeout(() => {
                this.camera.aspect = this.$refs.reccePage.$el.clientWidth / this.$refs.reccePage.$el.clientHeight;
                this.camera.updateProjectionMatrix();

                this.renderer.setSize(this.$refs.reccePage.$el.clientWidth, this.$refs.reccePage.$el.clientHeight);

                this.render();
            }, 200);

            // console.log(this.$refs.reccePage.$el.clientWidth, this.$refs.reccePage.$el.clientHeight, this.$refs.reccePage);

        },

        //初始化场景
        loadPreviewSys() {
            var renderer = new THREE.WebGLRenderer({
                antialias: true
            });
            renderer.setPixelRatio(window.devicePixelRatio);
            renderer.setSize(this.$refs.reccePage.$el.clientWidth, this.$refs.reccePage.$el.clientHeight);
            this.sceneHelpers = new THREE.Scene();
            let body = document.getElementById("three");
            body.appendChild(renderer.domElement);
            console.log(this.$refs.reccePage.$el.clientWidth, this.$refs.reccePage.$el.clientHeight);

            const aspect = this.$refs.reccePage.$el.clientWidth / this.$refs.reccePage.$el.clientHeight;

            var cameraPersp = new THREE.PerspectiveCamera(50, aspect, 0.01, 10000);
            let camera = cameraPersp;

            camera.position.set(20, 15, 20);
            camera.lookAt(0, 5, 0);
            this.camera = camera;
            var vm = this;

            var orbit = new OrbitControls(camera, renderer.domElement);
            orbit.update();

            orbit.addEventListener("change", vm.render);
            this.orbit = orbit;

            let scene = new THREE.Scene();
            this.grid = new THREE.GridHelper(50, 20);
            scene.add(this.grid);

            scene.background = new THREE.Color("#3f3f3f");
            this.scene = scene;
            this.camera.updateProjectionMatrix();

            renderer.setSize(this.$refs.reccePage.$el.clientWidth, this.$refs.reccePage.$el.clientHeight);

            var vm = this;

            // this.stats = new Stats();
            // body.appendChild(this.stats.dom);

            //this.stats.hidePanel();

            // renderer.outputEncoding = THREE.sRGBEncoding;
            // renderer.shadowMap.enabled = true;
            this.renderer = renderer;

            this.loadControl();
            // this.createHemlight();
            this.createAxis();
            this.control.attach(this.grid);
            this.control.visible = false;

            this.render();
            this.onWindowResize();

            window.addEventListener("resize", this.onWindowResize, false);

            var vm = this;

            window.addEventListener("keydown", function (event) {
                switch (event.keyCode) {
                    case 81: // Q
                        vm.control.setSpace(control.space === "local" ? "world" : "local");
                        break;

                    case 16: // shift
                        vm.control.setTranslationSnap(100);
                        vm.control.setRotationSnap(THREE.MathUtils.degToRad(15));
                        break;

                    case 84: // t
                        vm.control.setMode("translate");
                        break;

                    case 82: // r
                        vm.control.setMode("rotate");
                        break;

                    case 83: // s
                        vm.control.setMode("scale");
                        break;

                    case 187:
                    case 107: // +, =, num+
                        vm.control.setSize(control.size + 0.1);
                        break;

                    case 189:
                    case 109: // -, _, num-
                        vm.control.setSize(Math.max(control.size - 0.1, 0.1));
                        break;
                }
            });

            window.addEventListener("keyup", function (event) {
                switch (event.keyCode) {
                    case 17: // Ctrl
                        vm.control.setTranslationSnap(null);
                        vm.control.setRotationSnap(null);
                        break;
                }
            });
            // document.addEventListener("click", vm.onClick, false);
            // // document.onmousedown = function (e) {
            // //   console.log(e);
            // // };
            // document.addEventListener("touchstart", vm.onClick, false);
            var trackInfo = [{
                    type: THREE.VectorKeyframeTrack,
                    propertyPath: "MyBox.position",
                    initialValue: [0, 0, 0],
                    interpolation: THREE.InterpolateSmooth,
                },

                {
                    type: THREE.QuaternionKeyframeTrack,
                    propertyPath: "MyBox.quaternion",
                    initialValue: [0, 0, 0, 1],
                    interpolation: THREE.InterpolateLinear,
                },
            ];

            //
            function onWindowResize() {

            }
        },
        createAxis() {
            // var geometryX = new THREE.BufferGeometry();
            // var attribueX = new THREE.BufferAttribute(
            //   new Float32Array([
            //     0, 0.01, 0, 5, 0.01, 0, 5, 0.01, 0, 4.5, 0.01, -0.5, 5, 0.01, 0, 4.5,
            //     0.01, 0.5,
            //   ]),
            //   3
            // );
            // geometryX.attributes.position = attribueX;
            // var materialX = new THREE.LineBasicMaterial({
            //   color: 0xff0000,
            // });
            // var lineX = new THREE.Line(geometryX, materialX);
            // lineX.name = "axisX";
            // var geometryY = new THREE.BufferGeometry();
            // var attribueY = new THREE.BufferAttribute(
            //   new Float32Array([
            //     0,
            //     0,
            //     0, //顶点1坐标
            //     0,
            //     5,
            //     0, //顶点2坐标
            //     0,
            //     5,
            //     0,
            //     0,
            //     4.5,
            //     0.5,
            //     0,
            //     5,
            //     0,
            //     0,
            //     4.5,
            //     -0.5,
            //   ]),
            //   3
            // );
            // geometryY.attributes.position = attribueY;
            // var materialY = new THREE.LineBasicMaterial({
            //   color: 0x00ff00, //线条颜色
            // });
            // var lineY = new THREE.Line(geometryY, materialY);
            // lineY.name = "axisY";
            // var geometryZ = new THREE.BufferGeometry();
            // var attribueZ = new THREE.BufferAttribute(
            //   new Float32Array([
            //     0,
            //     0.01,
            //     0, //顶点1坐标
            //     0,
            //     0.01,
            //     5, //顶点2坐标
            //     0,
            //     0.01,
            //     5,
            //     0.5,
            //     0.01,
            //     4.5,
            //     0,
            //     0.01,
            //     5,
            //     -0.5,
            //     0.01,
            //     4.4,
            //   ]),
            //   3
            // );
            // geometryZ.attributes.position = attribueZ;
            // var materialZ = new THREE.LineBasicMaterial({
            //   color: 0x0000ff,
            // });
            // var lineZ = new THREE.Line(geometryZ, materialZ);
            // lineZ.name = "axisZ";
            // this.scene.add(lineX);
            // this.scene.add(lineY);
            // this.scene.add(lineZ);
        },
        onControlObjChange(e) {
            // console.log(e);
        },
        loadControl() {
            var vm = this;
            var control = new TransformControls(
                this.camera,
                this.renderer.domElement
            );

            this.control = control;
            this.control.addEventListener("change", vm.render);
            this.control.addEventListener("objectChange", vm.onControlObjChange);
            this.control.addEventListener("dragging-changed", function (event) {
                vm.orbit.enabled = !event.value;
            });
            this.scene.add(this.control);
        },

        onClick(event) {
            console.log(event);
            var mouse = new THREE.Vector2(),
                raycaster = new THREE.Raycaster();
            if (event.type !== "touchstart") {
                event.preventDefault();
                mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
                mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
            } else {
                mouse.x = (event.touches[0].clientX / window.innerWidth) * 2 - 1;
                mouse.y = -(event.touches[0].clientY / window.innerHeight) * 2 + 1;
            }

            raycaster.setFromCamera(mouse, this.camera);

            var intersections = raycaster.intersectObjects(this.objects, false);
            console.log(intersections);

            if (intersections.length > 0) {
                var object = intersections[0].object;
                console.log(this.objects);
                this.objects.forEach((item) => {
                    if (item.children.length > 0) {
                        item.children.forEach((eitem) => {
                            console.log(RegExp(/Helper/).test(eitem.type));
                            if (RegExp(/Helper/).test(eitem.type)) {
                                eitem.visible = false;
                            }
                        });
                    }
                });
                object.children.forEach((item) => {
                    if (RegExp(/Helper/).test(item.type)) {
                        item.visible = true;
                    }
                });

                this.control.attach(object);
                this.scene.attach(object);
            }

            // if ( group.children.length === 0 ) {

            // 	controls.transformGroup = false;
            // 	draggableObjects.push( ...objects );

            // }

            this.render();
        },

        //切换变换模式
        handleTransMode() {
            if (this.control.type) {
                if (this.transformMode == "t") {
                    this.control.setMode("translate");
                }
                if (this.transformMode == "s") {
                    this.control.setMode("scale");
                }
                if (this.transformMode == "r") {
                    this.control.setMode("rotate");
                }
            }
        },

        render() {
            this.renderer.render(this.scene, this.camera); //执行渲染操作
        },

        loadSceneBg(url) {
            this.grid.visible = false;
            var geometry = new THREE.SphereBufferGeometry(50, 60, 40);
            // invert the geometry on the x-axis so that all of the faces point inward
            geometry.scale(-1, 1, 1);
            console.log(url);

            const loader = new THREE.FileLoader();
            loader.load(
                url, onLoad, onProgress
            );
            var texture = new THREE.TextureLoader().load(
                url
            );
            var material = new THREE.MeshBasicMaterial({
                map: texture
            });
            var vm = this;

            function onLoad() {
                console.log('加载完成');
                vm.render()
            }

            function onProgress(xhr) {
                console.log('加载完成的百分比' + (xhr.loaded / xhr.total * 100) + '%');
            }
            let mesh = new THREE.Mesh(geometry, material);
            this.scene.add(mesh);



        },
        onPlay() {},
        onMainClick() {},
        onItemClick() {},
    },
};
</script>

<style scoped>
.preSys-wrap {
    width: 100%;
    height: 100%;
}

.controlPanel {
    position: absolute;
    top: 0;
    right: 0;
}

.bg-panel {
    background-color: #363636;
    border-radius: 5px;
}

.logo-img {
    height: 60px;
    max-width: 180px;
}
</style>
